package dao

import (
	"database/sql"
	"fmt"
)

// Transfer 转账例子, 测试事务
func Transfer(from, to string, money int64) error {
	tx, err := client.Begin()
	if err != nil {
		err = tx.Rollback()
		return err
	}

	result, err := tx.Exec("update t_balance set balance = balance - ? where name = ?",
		money, from)
	if err != nil {
		err = tx.Rollback()
		return err
	}
	affectedFrom, err := result.RowsAffected()
	if err != nil {
		err = tx.Rollback()
		return err
	}

	result, err = tx.Exec("update t_balance set balance = balance + ? where name = ?",
		money, to)
	if err != nil {
		err = tx.Rollback()
		return err
	}
	affectedTo, err := result.RowsAffected()
	if err != nil {
		err = tx.Rollback()
		return err
	}
	a := 0
	b := 10 / a
	fmt.Println(b)
	if affectedFrom == 1 && affectedTo == 1 {
		tx.Commit()
	} else {
		tx.Rollback()
	}

	return nil
}

func TransferWrapper(from, to string, money int64) error {
	// Decorator 模式
	return TxDecorator(func(tx *sql.Tx) error {
		result, err := tx.Exec("update t_balance set balance = balance - ? where name = ?",
			money, from)
		if err != nil {
			return err
		}
		_, err = result.RowsAffected()
		if err != nil {
			return err
		}

		//a := 0
		//b := 10 / 0
		//fmt.Println(a, b)
		panic(123) // 测试 panic 是否被捕获

		result, err = tx.Exec("update t_balance set balance = balance + ? where name = ?",
			money, to)
		if err != nil {
			return err
		}
		_, err = result.RowsAffected()
		if err != nil {
			return err
		}

		return nil
	})
}
